<?php

namespace CrontabConsole;

use yii\base\BaseObject;
use CrontabConsole\CronParser;

class Task extends BaseObject {

    public $id = '';
    public $name = '';
    public $route = ''; // 任务路由
    public $crontab_str = ''; //linux crontab解析符
    public $status = 0; // 任务状态: 0正常 1运行中 2任务出错
    public $switch = 1; // 任务开关: 0关 1开
    public $count = 0; // 运行次数
    public $last_rundate = ''; // 上次任务执行时间
    public $next_rundate = ''; // 下次任务执行时间
    public $exectime = 0; // 任务单次执行时长

    private static $cacheStr = [];

    public function calcNextRunDatetime() {
        if (isset(self::$cacheStr[$this->crontab_str])) {
            $this->next_rundate = self::$cacheStr[$this->crontab_str];
        } else {
            $this->next_rundate = CronParser::formatToDate($this->crontab_str)[0];
            self::$cacheStr[$this->crontab_str] = $this->next_rundate;
        }
    }

    public function toArray() 
    {
        return [
            'id' => $this->id,
            'route' => $this->route,
            'crontab_str' => $this->crontab_str,
            'status' => $this->status,
            'switch' => $this->switch,
            'count' => $this->count,
            'last_rundate' => $this->last_rundate,
            'next_rundate' => $this->next_rundate,
            'exectime' => $this->exectime,
        ];
    }

}